﻿/*-----------------------------------------------
// Copyright (C) 2020 钟平上  版权所有。
// 文件名称：    User
// 功能描述：    User 类
// 创建标识：    Shang 2021/3/20 星期六 23:26:14
// 修改标识：    Shang 2021/3/20 星期六 23:26:14
// 修改描述:
-----------------------------------------------*/

using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.Text;

namespace Blog.Core.Model.Model
{
    /// <summary>
    /// 用户
    /// </summary>
    public class User
    {
        private string password;
        public User()
        {
            UserName = $"user-{RandomString(5)}";
            password = EncryptPassword("123456" + UserName);
        }
        //public string ID { get; set; } = Guid.NewGuid().ToString();
        [Key]
        public string UserName { get; set; }
        public string Password
        {
            get => password;
            set
            {
                value ??= "123456";
                password = EncryptPassword(value + UserName);
            }
        } 
        public string Email { get; set; } = $"{RandomString()}@qq.com";
        public string Phone { get; set; } = RandomPhone();
        public bool State { get; set; } = true;

        public bool ValidatePassword(string password)=> EncryptPassword(password + UserName) == Password;
        
        static string RandomString(int length = 7)
        {
            return Guid.NewGuid().ToString("N").Remove(length);
        }
        static string RandomPhone()
        {
            var rd = new Random();
            string phone = "1";
            phone += rd.Next(3, 10).ToString();
            for (int i = 0; i < 9; i++)
            {
                phone += rd.Next(1, 10).ToString();
            }
            return phone;

        }
        private static string EncryptPassword(string passwordAndSalt)
        {
            MD5 md5 = MD5.Create();
            byte[] passwordAndSaltBytes = System.Text.Encoding.UTF8.GetBytes(passwordAndSalt);
            byte[] hs = md5.ComputeHash(passwordAndSaltBytes);
            StringBuilder sb = new StringBuilder();
            foreach (byte b in hs)
            {
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }
    }
}
